<template>
  <a-spin :spinning="false" v-if="model.billType == 'ORDER' && isadd">
    <div style="margin-top: 10px">
      <j-vxe-table-procurement
        keep-source
        :ref="refKeys[1]"
        :loading="tslProMaterialPickBillDetailTable.loading"
        :columns="tslProMaterialPickBillDetailTable.columns"
        :dataSource="tslProMaterialPickBillDetailTable.dataSource"
        :maxHeight="300"
        :disabled="false"
        :rowNumber="true"
        :rowSelection="false"
        :clickSelectRow="false"
        class="j-table-force-nowrap"
      >
      </j-vxe-table-procurement>
      <a-row :gutter="20" style="margin-top: 10px">
        <a-col :span="2">
          <a-button @click="doformula">下一步</a-button>
        </a-col>
      </a-row>
    </div>
  </a-spin>
  <a-spin :spinning="confirmLoading" v-else>
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" disabled placeholder="系统自动生成"></a-input>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="8">
            <a-form-model-item label="领料类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billType">
              <j-dict-select-tag type="list" :disabled="true" v-model="model.billType" dictCode="pick_bill_type" />
            </a-form-model-item>
          </a-col> -->
          <!-- <a-col :span="8">
            <a-form-model-item label="车间计划" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="workshopPlan">
              <a-input v-model="model.workshopPlan" disabled placeholder="请输入车间计划"></a-input>
            </a-form-model-item>
          </a-col> -->
          <!-- <a-col :span="8">
            <a-form-model-item label="生产车间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="workshopCode">
              <j-dict-select-tag type="list" v-model="model.workshopCode" disabled
                dictCode="sys_depart,depart_name,org_code,workshop_type is not null" placeholder="请选择所属车间" />
            </a-form-model-item>
          </a-col> -->
          <a-col :span="6">
            <a-form-model-item label="入库仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="wareNo">
              <a-select v-model="model.wareNo" placeholder="请选择入库仓库" style="width: 100%">
                <a-select-option v-for="item in houselist" :key="item.warehouseCode" :value="item.warehouseCode">
                  {{ item.warehouseName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="领料人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pickBy">
              <a-row :gutter="4">
                <a-col :span="18">
                  <a-input v-model="model.pickBy" placeholder="请选择领料人"></a-input>
                </a-col>
                <a-col :span="6">
                  <a-button @click="handleSelectEmployee" type="primary" :loading="confirmLoading">选择</a-button>
                </a-col>
              </a-row>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="领料部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pickOrgName">
              <a-input v-model="model.pickOrgName" placeholder="" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="领料日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pickDate">
              <j-date
                placeholder="请选择领料日期"
                v-model="model.pickDate"
                :show-time="true"
                date-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              label="备注"
              :labelCol="{ xs: { span: 24 }, sm: { span: 1 } }"
              :wrapperCol="{ xs: { span: 24 }, sm: { span: 22 } }"
              prop="remark"
            >
              <a-input v-model="model.remark" placeholder="请输入备注"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey">
      <a-tab-pane tab="原材明细" :key="refKeys[0]" :forceRender="true">
        <a-row :gutter="20" style="margin-bottom: 5px" v-if="model.billType == 'MANUAL'">
          <a-col :span="2">
            <a-button @click="addMaterial" :disabled="formDisabled">新增原料</a-button>
          </a-col>
        </a-row>
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="tslProWorkshopPlanScheduleTable.loading"
          :columns="tslProWorkshopPlanScheduleTable.columns"
          :dataSource="tslProWorkshopPlanScheduleTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="false"
        >
          <template v-slot:action="{ row }">
            <a-popconfirm title="确认删除?" @confirm="() => handleRemove(row)" :disabled="model.billType != 'MANUAL'">
              <a href="javascript:;" :disabled="model.billType != 'MANUAL'">删除</a>
            </a-popconfirm>
          </template>
        </j-vxe-table>
      </a-tab-pane>
    </a-tabs>
    <select-pick-user-modal ref="selectPickUserModal" @handlerOk="handleSelectEmployeeOk" />
    <!-- <erp-category-goods-list-modal
      ref="selectGoodsList"
      :modalWidth="modalWidth"
      :category="4"
      @goodRowsOk="goodsOk"
      checkval="checkbox"
    >
    </erp-category-goods-list-modal> -->
    <material-inventory ref="materialInventory" :category="4" @goodRowsOk="goodsOk" checkval="checkbox">
    </material-inventory>
  </a-spin>
</template>

<script>
import { getAction, postAction } from '@api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import JFormContainer from '@/components/jeecg/JFormContainer'
import store from '@/store'
import EmployeeListModal from '@/components/tsl/modules/EmployeeListModal.vue'
import { getDate } from '../../../utils'
import ErpCategoryGoodsListModal from '../../../components/base/modal/ErpCategoryGoodsListModal.vue'
import SelectPickUserModal from '../SelectPickUserModal.vue'
import MaterialInventory from './MaterialInventory.vue'

export default {
  name: 'TslProMaterialPickBillForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer,
    EmployeeListModal,
    ErpCategoryGoodsListModal,
    SelectPickUserModal,
    MaterialInventory,
  },
  data() {
    return {
      modalWidth: 1200,
      isadd: true,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: {},
      houselist: [],
      validatorRules: {
        // workshopCode: [{ required: true, message: '请选择领料车间!' }],
        wareNo: [{ required: true, message: '请选择入库仓库!' }],
        pickBy: [{ required: true, message: '请选择领料人!' }],
        pickDate: [{ required: true, message: '请选择领料日期!' }],
      },
      refKeys: ['tslProMaterialPickBillDetail', 'tslProMaterialPickBillProcess'],
      activeKey: 'tslProMaterialPickBillDetail',
      // 原料领料单子表
      tslProMaterialPickBillDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '车间计划',
            key: 'workshopPlanCode',
            type: JVXETypes.normal,
            minWidth: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '订单编号',
            key: 'orderCode',
            type: JVXETypes.normal,
            minWidth: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '配方号',
            key: 'formulaNumber',
            type: JVXETypes.normal,
            minWidth: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '生产锅',
            key: 'kettleName',
            type: JVXETypes.normal,
            minWidth: '200px',
            defaultValue: '',
          },
          {
            title: '锅数',
            key: 'kettleQuantity',
            type: JVXETypes.normal,
            minWidth: '120px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '已领料锅数',
            key: 'receivedQuantity',
            type: JVXETypes.normal,
            minWidth: '100px',
            placeholder: '请输入${title}',
            defaultValue: '0',
          },
          {
            title: '本次领料锅数',
            key: 'newQuantity',
            type: JVXETypes.input,
            minWidth: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
        ],
      },
      tslProWorkshopPlanScheduleTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '客户物料编码',
            key: 'customCode',
            type: JVXETypes.normal,
            minWidth: '140px',
            defaultValue: '',
          },
          {
            title: '物料编码',
            key: 'productCode',
            type: JVXETypes.normal,
            minWidth: '140px',
            defaultValue: '',
          },
          {
            title: '物料名称',
            key: 'productBatchNo',
            type: JVXETypes.normal,
            minWidth: 300,
            defaultValue: '',
          },
          {
            title: '规格型号',
            key: 'materialSpec',
            type: JVXETypes.normal,
            minWidth: '100px',
            defaultValue: '',
          },
          {
            title: '主计量单位',
            key: 'meUnit',
            dataIndex: 'meUnit',
            dictCode: 'ji_unit',
            type: JVXETypes.select,
            minWidth: 150,
            disabled: true,
          },
          //   {
          //     title: '辅单位',
          //     key: 'auUnit',
          //     dataIndex: 'auUnit',
          //     dictCode: 'zl_unit',
          //     type: JVXETypes.select,
          //     width: 150,
          //     disabled: true,
          //   },
          {
            title: '需求数量',
            key: 'planQuantity',
            dataIndex: 'planQuantity',
            defaultValue: '0',
            minWidth: 120,
          },
          {
            title: '库存可用数量',
            key: 'stockQuantity',
            dataIndex: 'stockQuantity',
            defaultValue: '0',
            minWidth: 120,
          },
          {
            title: '领料数量',
            key: 'receivedQuantity',
            dataIndex: 'receivedQuantity',
            type: JVXETypes.input,
            minWidth: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '100px',
            align: 'center',
            slotName: 'action',
          },
        ],
      },
      url: {
        add: '/pro/tslProMaterialPickBill/add',
        edit: '/pro/tslProMaterialPickBill/edit',
        queryById: '/pro/tslProMaterialPickBill/queryById',
        warehouseList: '/wms/basic/warehouse/list',
        queryByMainIds: '/pro/tslProWorkshopPlan/queryByMainIds',
        tslProMaterialPickBillDetail: '/pro/tslProMaterialPickBill/queryTslProMaterialPickBillDetailByMainId',
      },
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {},
  methods: {
    addMaterial() {
      this.$nextTick(() => {
        this.$refs.materialInventory.add()
      })
    },
    handleRemove(key) {
      const dataSource = [...this.tslProWorkshopPlanScheduleTable.dataSource]
      this.tslProWorkshopPlanScheduleTable.dataSource = dataSource.filter((item) => item.id !== key.id)
    },
    //选择员工方法
    handleSelectEmployeeOk(data) {
      console.log('选择员工：', data)
      if (data) {
        this.model.pickBy = data.realname
        this.model.pickOrgCode = data.orgCode
        this.model.pickOrgName = data.orgCodeTxt
        this.$forceUpdate() //重新渲染UI
      }
    },
    //绑定所属员工
    handleSelectEmployee() {
      this.$refs.selectPickUserModal.visible = true
    },
    add(ids, workshopCode) {
      this.reset()
      this.isadd = true
      this.model.workshopCode = workshopCode
      getAction(this.url.warehouseList, {
        pageSize: 999,
        pageNo: 1,
        warehouseType: 8,
        sysOrgCode: workshopCode,
      }).then((res) => {
        if (res.success) {
          this.houselist = res.result.records
          if (this.houselist != null && this.houselist.length > 0) {
            this.model.wareNo = this.houselist[0].warehouseCode
          }
        }
      })
      if (ids && ids.length > 0) {
        this.model.billType = 'ORDER'
        const modalFooter = document.querySelector('.ant-modal-footer')
        if (modalFooter) {
          modalFooter.style.display = 'none'
        }
        postAction(this.url.queryByMainIds, { ids: ids }).then((res) => {
          if (res.result && res.result.length > 0) {
            res.result.forEach((item) => {
              item.receivedQuantity = item.receivedQuantity || 0
              item.actualNumber = item.actualNumber || 0
            })
            this.tslProMaterialPickBillDetailTable.dataSource = res.result
          }
        })
      } else {
        this.model.billType = 'MANUAL'
      }
    },
    doformula() {
      if (this.model.billType == 'MANUAL') {
        return false
      }
      let hasMissingFields = false
      this.tslProMaterialPickBillDetailTable.dataSource.forEach((row, index) => {
        if (!row.newQuantity || row.newQuantity === '') {
          hasMissingFields = true
          this.$message.error(`第 ${index + 1} 行的本次领料锅数不能为空`)
        } else {
          const kettleQuantity = Number(row.kettleQuantity) || 0
          const receivedQuantity = Number(row.receivedQuantity) || 0
          if (kettleQuantity < receivedQuantity + Number(row.newQuantity)) {
            hasMissingFields = true
            this.$message.error(`第 ${index + 1} 行的领料锅数不能大于锅数`)
          }
        }
      })
      if (hasMissingFields) return

      this.isadd = false
      const modalFooter = document.querySelector('.ant-modal-footer')
      if (modalFooter) {
        modalFooter.style.display = 'block'
      }
      let details = []
      this.tslProMaterialPickBillDetailTable.dataSource.forEach((row) => {
        if (row.tslProScheduleDetail && row.tslProScheduleDetail.length > 0) {
          row.tslProScheduleDetail.forEach((item) => {
            details.push({
              planQuantity: (item.actualNumber * row.newQuantity).toFixed(6),
              formulaCode: item.formulaCode,
              formulaName: item.formulaName,
              formulaNumber: item.formulaNumber,
              productCode: item.productCode,
              productBatchNo: item.productBatchNo,
              materialSpec: item.materialSpec,
              meUnit: item.meUnit,
              stockQuantity: item.stockQuantity,
              customCode: item.customCode,
              auUnit: item.auUnit,
              workshopPlanId: row.workshopPlanId,
            })
          })
        }
      })
      const grouped = details.reduce((acc, current) => {
        const existing = acc.find((item) => item.productCode === current.productCode)
        if (existing) {
          existing.planQuantity = (parseFloat(existing.planQuantity) + parseFloat(current.planQuantity)).toFixed(6)
        } else {
          acc.push({ ...current })
        }
        return acc
      }, [])
      grouped.forEach((item) => {
        item.receivedQuantity = item.planQuantity
        item.stockQuantity = item.stockQuantity || 0
      })
      this.tslProWorkshopPlanScheduleTable.dataSource = grouped
    },
    edit(record) {
      this.model = record
      getAction(this.url.warehouseList, {
        pageSize: 999,
        pageNo: 1,
        warehouseType: 8,
        sysOrgCode: record.workshopCode,
      }).then((res) => {
        if (res.success) {
          this.houselist = res.result.records
        }
      })
      this.isadd = false
      this.model.pickOrgName = record.pickOrgCode_dictText
      this.tslProWorkshopPlanScheduleTable.dataSource = []
      getAction(this.url.tslProMaterialPickBillDetail, { id: record.id }).then((res) => {
        if (res.success) {
          res.result.forEach((item) => {
            item.stockQuantity = item.stockQuantity || 0
          })
          this.tslProWorkshopPlanScheduleTable.dataSource = res.result
        }
      })
    },
    async handleOk() {
      //  校验主表单
      const mainFormValid = await new Promise((resolve) => {
        this.$refs.form.validate((valid) => resolve(valid))
      })
      if (!mainFormValid) return

      let hasMissingFields = false
      this.tslProWorkshopPlanScheduleTable.dataSource.forEach((row, index) => {
        if (!row.receivedQuantity || row.receivedQuantity === '') {
          hasMissingFields = true
          this.$message.error(`第 ${index + 1} 行的领料数量不能为空`)
        } else if (this.model.billType == 'ORDER') {
          const planQuantity = Number(row.planQuantity) || 0
          const receivedQuantity = Number(row.receivedQuantity) || 0
          const stockQuantity = Number(row.stockQuantity) || 0
          if (receivedQuantity > planQuantity) {
            hasMissingFields = true
            this.$message.error(`第 ${index + 1} 行的领料数量不能大于需求数量`)
          } else if (receivedQuantity > stockQuantity) {
            hasMissingFields = true
            this.$message.error(`第 ${index + 1} 行的领料数量不能大于库存可用数量`)
          }
        }
      })
      if (hasMissingFields) return

      //  调用接口提交（根据实际接口调整）
      this.confirmLoading = true
      this.model.tslProMaterialPickBillDetailList = this.tslProWorkshopPlanScheduleTable.dataSource
      this.model.tslProWorkPlanProcessDetailList = this.tslProMaterialPickBillDetailTable.dataSource
      try {
        const url = this.model.code ? this.url.edit : this.url.add // 编辑/新增判断
        await postAction(url, this.model)
        this.$message.success('提交成功')
        this.$emit('ok') // 触发提交成功事件，通知模态框
      } catch (error) {
        this.$message.error('提交失败：' + (error.message || '网络异常'))
      } finally {
        this.confirmLoading = false
      }
    },
    goodsOk(datas) {
      const that = this
      const ids = that.tslProWorkshopPlanScheduleTable.dataSource.map((item) => item.productCode)
      if (datas && datas.length > 0) {
        datas.forEach((item) => {
          if (ids.indexOf(item.code) < 0) {
            let detail = {}
            detail.customCode = item.customerMaterialCode
            detail.productCode = item.materialCode
            detail.productBatchNo = item.materialName
            detail.materialSpec = item.specificationModel
            detail.stockQuantity = item.quantity
            detail.auUnit = item.secondaryUnit
            detail.meUnit = item.unit
            that.tslProWorkshopPlanScheduleTable.dataSource.push(detail)
          }
        })
      }
    },
    reset() {
      let d = getDate('day', 0)
      this.model = {
        id: undefined,
        code: undefined,
        billType: undefined,
        workshopCode: '',
        wareNo: '',
        workshopPlan: '',
        pickBy: '',
        pickDate: d,
        remark: '',
      }
    },
    addBefore() {
      this.tslProMaterialPickBillDetailTable.dataSource = []
      this.tslProWorkshopPlanScheduleTable.dataSource = []
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
  },
}
</script>

<style scoped>
::v-deep .vxe-table--body-wrapper {
  max-height: 100% !important;
}
::v-deep .ant-pagination {
  margin-top: 10px;
  float: right;
}
</style>
